import ctypes
from pyglet.gl import *
from pyglet.GLU import *


def generateSelectionRay(x, y):
    global space
    # Based on: http://nehe.gamedev.net/data/articles/article.asp?article=13
    fouriv = ctypes.c_int * 4
    sixteendv = ctypes.c_double * 16
    viewport = fouriv() # Where The Viewport Values Will Be Stored
    glGetIntegerv(GL_VIEWPORT, viewport) # Retrieves The Viewport Values (X, Y, Width, Height)
    modelview = sixteendv() # Where The 16 Doubles Of The Modelview Matrix Are To Be Stored
    glGetDoublev(GL_MODELVIEW_MATRIX, modelview) # Retrieve The Modelview Matrix
    projection = sixteendv() # Where The 16 Doubles Of The Projection Matrix Are To Be Stored
    glGetDoublev(GL_PROJECTION_MATRIX, projection) # Retrieve The Projection Matrix 

    def unProject(x, y, z, modelview, projection):
        X = ctypes.c_double()
        Y = ctypes.c_double()
        Z = ctypes.c_double()
        result = gluUnProject(ctypes.c_double(x), ctypes.c_double(y), ctypes.c_double(z), modelview, 
            projection, viewport, ctypes.byref(X), ctypes.byref(Y), ctypes.byref(Z));
        return [X.value, Y.value, Z.value]

    return [
        unProject(x, y, 0., modelview, projection),
        unProject(x, y, 1., modelview, projection)
    ]
